package com.xiaohao.communication.daoImpl;


import com.mongodb.client.result.UpdateResult;
import com.xiaohao.communication.bean.Integration;
import com.xiaohao.communication.dao.UserIntegrationDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;


/*
* 用户积分模块（活跃值）
* */
@Repository
public class UserIntegrationDaoImpl implements UserIntegrationDao {


    @Autowired
    MongoTemplate mongoTemplate;

    //获取用户积分
    @Override
    public List<Integration> getUserIntegration(int id) {
        Query query = new Query(Criteria.where("user_id").is(id));
        List<Integration> integration = mongoTemplate.find(query, Integration.class, "integration");

        return integration;
    }

    //增加用户积分
    @Override
    public void addUserIntegration(Integration integration) {

        int user_id = integration.getUser_id();
        int addIntegralNum = integration.getIntegralNumber();

        //获取数据库中的积分。
        Query query = new Query(Criteria.where("user_id").is(user_id));
        List<Integration> integration1 = mongoTemplate.find(query, Integration.class, "integration");
        Integration integration2 = integration1.get(0);
        int oldIntegralNumber = integration2.getIntegralNumber();

        //更新数据库积分
        Update update = new Update();
        update.set("integralNumber",oldIntegralNumber+addIntegralNum);
        mongoTemplate.updateFirst(query, update, Integration.class);


    }


    //减少用户积分
    @Override
    public void reduceUserIntegration(Integration integration) {
        int user_id = integration.getUser_id();
        int reduceIntegralNum = integration.getIntegralNumber();

        //获取数据库中的积分。
        Query query = new Query(Criteria.where("user_id").is(user_id));
        List<Integration> integration1 = mongoTemplate.find(query, Integration.class, "integration");
        Integration integration2 = integration1.get(0);
        int oldIntegralNumber = integration2.getIntegralNumber();

        //更新数据库积分
        Update update = new Update();
        update.set("integralNumber",oldIntegralNumber-reduceIntegralNum);
        mongoTemplate.updateFirst(query,update,Integration.class);


    }


}
